import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

public class IRCServer {
	private ServerSocket serverSoc;
	private Socket socket;
	private HashMap<String, Channel> channelList;
	private HashMap<String, User> userList;
	public String realName;
	private int port;
	
	public IRCServer(){
		port = 25003;
		try {
			serverSoc = new ServerSocket(port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		}
		channelList = new HashMap<String, Channel>();
		userList = new HashMap<String, User>();
	}

	public void listen() {

		while (true) {
			try {
				socket = serverSoc.accept();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			User user = new User(socket, this);
			user.run();
		}
	}

	public boolean channelAdder(String channelName, User user){
		if (!channelList.containsKey(channelName)){
			Channel channel = new Channel(channelName);
			channel.add(user);
			channelList.put(channelName, channel);
			return true;
		}else if(channelList.containsKey(channelName)){
			channelList.get(channelName).add(user);
			return true;
		}
			return false;
		}
	public void channelLeaver(String channelName, User user){
		if(channelList.containsKey(channelName)){
			channelList.get(channelName).remove(user);
			if(channelList.get(channelName).size() < 1){
			channelList.remove(channelName);
			}
	} //must send message to everyone in channel that we left
	}
	
	public void EvalCommand(IRCCommand cmd, User user) {

	}

	public boolean registerOrChangeNick(String Nick, User user) {
		if (!userList.containsKey(Nick)) {
			userList.put(Nick, user);
			if (userList.containsKey(user.getNick()) && user.getNick() != null) {
				userList.remove(user.getNick());
			}
			return true; // new user added

		} else return false; // user or nick already exists
		

	}

	/**
	 * public static void main(String[] args) {
	 * 
	 * 
	 * 
	 * Vector<User> userList = new Vector<User>(); MessageHandler MSGHandler;
	 * //flush? User user; ChannelMonitor cm;
	 * 
	 * try { server = new ServerSocket(port); //cm = new ChannelMonitor(user);
	 * //varför blir det rött? MSGHandler = new MessageHandler(userList);
	 * 
	 * while(true){ socket = server.accept(); String name =
	 * socket.getInetAddress().getHostName(); user = new User(socket, name);
	 * userList.add(user);
	 * 
	 * user.run(); } } catch (IOException e) { System.out.println(e);
	 * System.exit(1); } }
	 **/

}
